package com.phicomm.cloud.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/msg")
public class MsgController {

	private static final Logger logger =  LoggerFactory.getLogger(MsgController.class);

	@RequestMapping("HttpBatchSendSM")
	public String HttpBatchSendSM(ModelMap map, @RequestParam String login,@RequestParam String pass,
								 @RequestParam(required = false) String to,@RequestParam(required = false) String message){
		String url= "http://222.73.117.158/msg/HttpBatchSendSM";
		String param="account="+login+"&pswd="+pass+"&mobile="+to+"&msg="+java.net.URLEncoder.encode(message)+"&needstatus=true&extno=218";
		String result=sendGet(url, param);
//		System.out.println("result--->"+result);
		return result;
	}

	@RequestMapping("QueryBalance")
	public String QueryBalance(ModelMap map, @RequestParam String login,@RequestParam String pass){
		String url= "http://222.73.117.158/msg/QueryBalance";
		String param="account="+login+"&pswd="+pass;
		String result=sendGet(url, param);
//		System.out.println("result--->"+result);
		return result;
	}

	public String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
//			System.out.println(urlNameString);
//			logger.warn(urlNameString);
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			// 设置超时时间
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			// 建立实际的连接
			connection.connect();

			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			for (String key : map.keySet()) {
//				System.out.println(key + "--->" + map.get(key));
			}

			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}
}
